<template>
  <div class="chagepsd-container">
    <div class="title">修改密码</div>
    <van-form @submit="onSubmit" ref="form">
      当前密码
      <van-field
        v-model="password"
        type="password"
        placeholder="请输入当前登录密码"
        clearable
        :rules="[{ required: true, message: '请填写当前登录密码' }]"
      />
      新密码
      <van-field
        v-model="newpassword"
        placeholder="请输入新密码"
        clearable
        name="validator"
        type="password"
        :rules="[{ required: true, message: '请填写新密码' }]"
      />
      重复密码
      <van-field
        v-model="confirmpassword"
        placeholder="请重复密码"
        clearable
        type="password"
        name="validator"
        :rules="[
          { required: true, message: '请重复填写密码' },
          {
            validator,
            message: '两次密码不唯一'
          }
        ]"
      />
      <div
        :class="{
          unsubmit: !issubmit,
          submit: issubmit
        }"
      >
        <van-button round block native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { changepassword } from "@/api/user";
export default {
  name: "Changepsd",
  data() {
    return {
      confirmpassword: "",
      newpassword: "",
      password: "",
      issubmit: false,
      userData: {}
    };
  },
  watch: {
    newpassword(val) {
      this.$refs.form
        .validate()
        .then(() => {
          this.issubmit = true;
        })
        .catch(() => {
          this.issubmit = false;
        });
    },
    confirmpassword(val) {
      this.$refs.form
        .validate()
        .then(() => {
          this.issubmit = true;
        })
        .catch(() => {
          this.issubmit = false;
        });
    },
    password(val) {
      this.$refs.form
        .validate()
        .then(() => {
          this.issubmit = true;
        })
        .catch(() => {
          this.issubmit = false;
        });
    }
  },
  beforeCreate() {},
  created() {},
  mounted() {
    this.userData = JSON.parse(localStorage.getItem("userData"));
  },
  methods: {
    validator(val) {
      return val == this.newpassword;
    },
    onSubmit() {
      this.$refs.form
        .validate()
        .then(async () => {
          changepassword({
            id: this.userData.id,
            password: this.password,
            newpassword: this.newpassword
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
